package com.bangdream.michelia.utils;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.bangdream.michelia.application.MainApplication;

import java.io.File;
import java.net.InetAddress;
import java.text.DecimalFormat;
import java.util.Locale;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Created by Administrator on 2016/9/1.
 * 工具类
 */
public class PublicUtil {
	private static final String TAG = "PublicUtil";
	public static final String ProjectName = "WalkWorld";
	public static final String LocalPath = Environment.getExternalStorageDirectory().getPath() + "/"+ProjectName;
	public static final String LocalImageCachePath = "/PictureCache";										//图片缓存地址
	public static final String LocalImagePath = "/picture";													//存放图片地址
	public static final String LocalVideoPath = "/video";													//存放视频地址
	public static final String LocalVoicePath = "/voice";													//存放音频地址
	public static final String LocalDownLoadPath = "/DownLoadFile";											//存放下载文档地址
	public static final int WizardResultCode = 1;															//向导页返回标识码

	public static final String MSG_TYPE_TEXT="1";//文本消息
	public static final String MSG_TYPE_IMG="2";//图片
	public static final String MSG_TYPE_VOICE="3";//语音
	public static final String MSG_TYPE_LOCATION="msg_type_location";//位置
	public static final String MSG_TYPE_MUSIC="msg_type_music";//音乐
	public static final String MSG_TYPE_LIST="msg_type_list";//新闻


	private Activity activity;
	//判断字符串是否为网址的正则表达式
	public static final Pattern pattern = Pattern
			//.compile("^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+$");
			.compile("(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?");
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /// rc4加密解密,按char运算，匹配前端js的算法
    /// </summary>
    /// <param name="data"></param>
    /// <param name="pass"></param>
    /// <returns></returns>
    public static String RC4(String data, String pass)
    {
        if (data==null || pass==null) {
            return "";
        }
        char[] output = new char[data.length()];

        int j = 0;
        int kLen = 256;
        char[] mBox = new char[kLen];
        for (int k = 0; k < kLen; k++)
            mBox[k] = (char)k;

        for (int k = 0; k < kLen; k++)
        {
            j = (j + mBox[k] + pass.charAt(k % pass.length())) % kLen;
            char temp = mBox[k];
            mBox[k] = mBox[j];
            mBox[j] = temp;
        }
        // 加密
        int i = data.length();
        for (int offset = 0; offset < data.length(); offset++)
        {
            i = (i + 1) % mBox.length;
            j = (j + mBox[i]) % mBox.length;
            char temp = mBox[i];
            mBox[i] = mBox[j];
            mBox[j] = temp;
            char a = data.charAt(offset);
            //Byte b = mBox[(mBox[i] + mBox[j] % mBox.Length) % mBox.Length];
            // mBox[j] 一定比 mBox.Length 小，不需要在取模
            char b = mBox[(mBox[i] + mBox[j]) % mBox.length];
            output[offset] = (char)((int)a ^ (int)b);
        }
        return new String(output);
    }

	/**
     * 判断当前系统语言是否中文
     * @return
     */
    public static boolean isZh() {
        Locale locale = MainApplication.getContext().getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        if (language.endsWith("zh"))
            return true;
        else
            return false;
    }

	public static String getUUid()
	{
		UUID uuid = UUID.randomUUID();
		MyLog.e(TAG,"uuid=================="+uuid.toString());
		return uuid.toString();
	}
	//更新媒体库 如视频拍摄完 更新视频库
	public static void updateMediaDataBase(Context context,String filename) {
		int currentApiVersion = Build.VERSION.SDK_INT;// 获得当前sdk版本
		if (currentApiVersion < 19) {
			context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
					Uri.parse("file://" + filename)));
		} else {
			MediaScannerConnection.scanFile(context, new String[] { filename },
					null, new MediaScannerConnection.OnScanCompletedListener() {
						public void onScanCompleted(String path, Uri uri) {
							Log.i("ExternalStorage", "Scanned " + path + ":");
							Log.i("ExternalStorage", "-> uri=" + uri);
						}
					});
		}
	}


	//判断某个格式是否需要下载才能查看 如word pdf
	public static boolean isDownloadFile(String Suffix) {
		if (Suffix.equals(".doc")
				|| Suffix.equals(".docx")
				|| Suffix.equals(".pdf")
				|| Suffix.equals(".xls")
				|| Suffix.equals(".xlsx")
				|| Suffix.equals(".ppt")
				|| Suffix.equals(".pptx"))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	//打开附件 如word pdf
	public static void openFile(Context context,File file){
		try{
			Intent intent = new Intent();
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			//设置intent的Action属性
			intent.setAction(Intent.ACTION_VIEW);
			//获取文件file的MIME类型
			String type = getMIMEType(file);
			//设置intent的data和Type属性。
			intent.setDataAndType(/*uri*/Uri.fromFile(file), type);
			//跳转
			context.startActivity(intent);
//      Intent.createChooser(intent, "请选择对应的软件打开该附件！");
		}catch (ActivityNotFoundException e) {
			// TODO: handle exception
			Toast.makeText(context, "附件不能打开，请下载相关软件！", Toast.LENGTH_SHORT).show();
		}
	}


	private static String getMIMEType(File file) {

		String type="*/*";
		String fName = file.getName();
		//获取后缀名前的分隔符"."在fName中的位置。
		int dotIndex = fName.lastIndexOf(".");
		if(dotIndex < 0){
			return type;
		}
        /* 获取文件的后缀名*/
		String end=fName.substring(dotIndex,fName.length()).toLowerCase();
		if(end=="")return type;
		//在MIME和文件类型的匹配表中找到对应的MIME类型。
		for(int i=0;i<MIME_MapTable.length;i++){
			if(end.equals(MIME_MapTable[i][0]))
				type =MIME_MapTable[i][1];
		}
		return type;
	}

	// 可以自己随意添加
	static String [][]  MIME_MapTable={
			//{后缀名，MIME类型}
			{".3gp",    "video/3gpp"},
			{".apk",    "application/vnd.android.package-archive"},
			{".asf",    "video/x-ms-asf"},
			{".avi",    "video/x-msvideo"},
			{".bin",    "application/octet-stream"},
			{".bmp",    "image/bmp"},
			{".c",  "text/plain"},
			{".class",  "application/octet-stream"},
			{".conf",   "text/plain"},
			{".cpp",    "text/plain"},
			{".doc",    "application/msword"},
			{".docx",   "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
			{".xls",    "application/vnd.ms-excel"},
			{".xlsx",   "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
			{".exe",    "application/octet-stream"},
			{".gif",    "image/gif"},
			{".gtar",   "application/x-gtar"},
			{".gz", "application/x-gzip"},
			{".h",  "text/plain"},
			{".htm",    "text/html"},
			{".html",   "text/html"},
			{".jar",    "application/java-archive"},
			{".java",   "text/plain"},
			{".jpeg",   "image/jpeg"},
			{".jpg",    "image/jpeg"},
			{".js", "application/x-javascript"},
			{".log",    "text/plain"},
			{".m3u",    "audio/x-mpegurl"},
			{".m4a",    "audio/mp4a-latm"},
			{".m4b",    "audio/mp4a-latm"},
			{".m4p",    "audio/mp4a-latm"},
			{".m4u",    "video/vnd.mpegurl"},
			{".m4v",    "video/x-m4v"},
			{".mov",    "video/quicktime"},
			{".mp2",    "audio/x-mpeg"},
			{".mp3",    "audio/x-mpeg"},
			{".mp4",    "video/mp4"},
			{".mpc",    "application/vnd.mpohun.certificate"},
			{".mpe",    "video/mpeg"},
			{".mpeg",   "video/mpeg"},
			{".mpg",    "video/mpeg"},
			{".mpg4",   "video/mp4"},
			{".mpga",   "audio/mpeg"},
			{".msg",    "application/vnd.ms-outlook"},
			{".ogg",    "audio/ogg"},
			{".pdf",    "application/pdf"},
			{".png",    "image/png"},
			{".pps",    "application/vnd.ms-powerpoint"},
			{".ppt",    "application/vnd.ms-powerpoint"},
			{".pptx",   "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
			{".prop",   "text/plain"},
			{".rc", "text/plain"},
			{".rmvb",   "audio/x-pn-realaudio"},
			{".rtf",    "application/rtf"},
			{".sh", "text/plain"},
			{".tar",    "application/x-tar"},
			{".tgz",    "application/x-compressed"},
			{".txt",    "text/plain"},
			{".wav",    "audio/x-wav"},
			{".wma",    "audio/x-ms-wma"},
			{".wmv",    "audio/x-ms-wmv"},
			{".wps",    "application/vnd.ms-works"},
			{".xml",    "text/plain"},
			{".z",  "application/x-compress"},
			{".zip",    "application/x-zip-compressed"},
			{"",        "*/*"}
	};

	/**
	 * 获取本地Ip地址
	 *
	 * @param activity
	 * @return
	 */
	public static String getLocalIpAddress(Activity activity) {
		try {
			WifiManager wifi;
			wifi = (WifiManager) activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
			WifiInfo info = wifi.getConnectionInfo();
			int ipAddress = info.getIpAddress();
			String Ipv4Address = InetAddress
					.getByName(
							String.format("%d.%d.%d.%d", (ipAddress & 0xff),
									(ipAddress >> 8 & 0xff),
									(ipAddress >> 16 & 0xff),
									(ipAddress >> 24 & 0xff))).getHostAddress();
			return Ipv4Address;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	//判断字符串是否为手机号
	public static boolean isMobileNO(String mobiles){

		Pattern p = Pattern.compile("^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|166|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$");

		Matcher m = p.matcher(mobiles);

		MyLog.d(TAG,m.matches()+"---");

		return m.matches();

	}

	//判断字符串是否为手机号
	public static boolean isEmailNO(String EmailNO){

		Pattern pattern = Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
		Matcher matcher = pattern.matcher(EmailNO);
		MyLog.d(TAG,matcher.matches()+"---");
		return matcher.matches();

	}

	/**
	 * 防止滑动listView到顶部或底部时出现蓝边现象
	 *
	 * @param listView
	 */
	public static void setOverScrollMode(ListView listView) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO)
			listView.setOverScrollMode(View.OVER_SCROLL_NEVER);
	}

	//删除文件或文件夹
	public static void deleteFile(File file) {
		        if (file.isFile()) {
			           file.delete();
			         return;
			        }
		     if(file.isDirectory()){
			           File[] childFiles = file.listFiles();
			            if (childFiles == null || childFiles.length == 0) {
			              file.delete();
			               return;
			            }

		          for (int i = 0; i < childFiles.length; i++) {
					  deleteFile(childFiles[i]);
			           }
			           file.delete();
			       }
		    }


	public static String tranForm(String time){
		if(time!=null && !time.isEmpty()){
			Double aDouble = Double.valueOf(time)/60;

			DecimalFormat decimalFormat = new DecimalFormat("#0.00");
			return decimalFormat.format(aDouble);
		}else{
			return "0";
		}
	}
	public static String tranForm2(String time){
		if(time!=null && !time.isEmpty()){
			Double aDouble = Double.valueOf(time)/60/60;

			DecimalFormat decimalFormat = new DecimalFormat("#0.00");
			return decimalFormat.format(aDouble);
		}else{
			return "0";
		}
	}
}
